package com.zxl.live.screen.ui.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

/**
 * Created by Administrator on 2017/11/10.
 */

public class GeometricLinearLayout extends FrameLayout implements ViewTreeObserver.OnGlobalLayoutListener {

    public GeometricLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setBackground(Drawable background) {
        super.setBackground(background);
        getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    @Override
    public void onGlobalLayout() {
        Drawable drawable = getBackground();
        if (BitmapDrawable.class.isInstance(drawable)) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();

            float scale = (float) getWidth() / bitmap.getWidth();
            int height = (int) (scale * bitmap.getHeight());
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();
            layoutParams.height = height;
            setLayoutParams(layoutParams);
            getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
    }
}
